# _*_coding:utf-8 _*_
# @ Time　　 : 2022/12/12 16:51
# @ Author　 : 郭鑫垚
# @ class　  : 数据201

import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from pyecharts import options as opts
from pyecharts.charts import Geo, Map
from pyecharts.globals import ChartType, SymbolType
from pyecharts.globals import ThemeType

plt.rcParams["font.sans-serif"] = [u"SimHei"]
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams.update({'font.size': 8})  # 设置字体大小


# 价格数据分析可视化
def price_plt(data):
    price_cut = pd.cut(data['价格/万'], bins=[0, 10, 20, 30, 40, 50, 100],
                       labels=['0-10', '10-20', '20-30', '30-40', ' 40-50', '>50'])
    price_counts = price_cut.value_counts().sort_index()
    # print(price1_cut.value_counts())
    plt.figure(figsize=(10, 6))
    plt.suptitle('二手车价格数据分析')
    # 全款价格柱状图分析
    plt1 = plt.subplot(1, 2, 1)
    x1 = np.arange(len(price_counts))
    y1 = price_counts
    plt1.bar(x1, y1, color='r', alpha=0.3)
    plt1.set_title("二手车价格分布图")
    plt1.set_xlabel('价格区间/(万元)')
    plt1.set_ylabel('数量/(辆)')
    plt1.set_xticks(np.arange(len(price_counts)))
    plt1.set_xticklabels(price_counts.index, rotation=30)
    # plt1.set_ylim([0, 300])
    for x, y, z in zip(x1, y1, price_counts):
        plt1.text(x - 0.2, y + 4, z)
    plt1.set_title("二手车全款价格柱状图/(万元)")
    # 全款价格饼状图
    plt2 = plt.subplot(1, 2, 2)
    list = []
    for i1 in price_counts / price_counts.sum():
        # print(i1)
        list.append(i1)
    # print(list)
    labels = ['0-10', '10-20', '20-30', '30-40', ' 40-50', '>50']
    plt2.pie(x=list,  # 绘图的数据
             labels=labels,  # 数据标签
             # colors=colors,  # 饼图颜色
             autopct="%.1f%%",  # 设置百分比
             startangle=180,  # 设置初始角度
             radius=2,  # 设置饼的半径
             normalize=True,
             # labeldistance=1.3
             )
    plt2.set_title('二手车全款价格占比')
    plt.subplots_adjust(wspace=0.5, hspace=0.5)
    # plt.show()
    plt.savefig(fname="../img/价格分析.jpg", dpi=1000, facecolor="w")
    print("价格简单分析图已保存")


# 实现车龄数据可视化分析
def age_plt(data):
    # 设置画布大小
    plt.figure(figsize=(10, 6))
    plt.suptitle('二手车车龄数据分析')
    # 全款价格柱状图分析
    plt1 = plt.subplot(2, 2, 1)
    # age_cut将所有的Sec_age的值划分到相应的区间中
    Sec_age_min = data.车龄.min()
    Sec_age_max = data.车龄.max()
    # print(Sec_age_max, Sec_age_min)  # 查看最值
    age_cut = pd.cut(data.车龄, bins=[-1, 3, 5, 8, 10, 20], labels=['0-3', '3-5', '5-8', '8-10', '>10'])
    # print(age_cut)
    age_count = age_cut.value_counts().sort_index()
    # print(age_count)
    # 查看占比情况
    list = []
    for i1 in age_count / age_count.sum():
        # print(i1)
        list.append(i1)
    # print(list)
    labels = ['0-3', '3-5', '5-8', '8-10', '>10']
    # colors = ["green", "blue", "red", "yellow", "pink"]
    # explode = [0.1, 0, 0, 0, 0]

    plt1.pie(x=list,  # 绘图的数据
             labels=labels,  # 数据标签
             # colors=colors,  # 饼图颜色
             autopct="%.1f%%",  # 设置百分比
             startangle=180,  # 设置初始角度
             # frame=1,
             # center=(2,2)
             # explode=explode,  # 设置突出显示
             radius=1.8  # 设置饼的半径
             )
    plt1.set_title('瓜子二手车车龄占比')

    #  绘制不同价格区间占比情况的柱形图
    plt2 = plt.subplot(2, 2, 2)
    Sec_year_min = data.上牌年份.min()
    Sec_year_max = data.上牌年份.max()
    # print(Sec_year_min, Sec_year_max)  # 查看最值
    year_cut = pd.cut(data.上牌年份, bins=np.arange(2005, 2023), labels=np.arange(2006, 2023))
    # print(type(year_cut))
    year_count = year_cut.value_counts().sort_index()
    # print(year_count.sort_index())
    x2 = np.arange(len(age_count))
    y2 = age_count
    plt2.bar(x2, y2, color='g', alpha=0.3)
    plt2.set_title("瓜子二手车车龄分布图")
    plt2.set_xlabel('车龄区间/年')
    plt2.set_ylabel('数量/(辆)')
    plt2.set_xticks(np.arange(len(age_count)))
    plt2.set_xticklabels(age_count.index, rotation=30)
    for x, y, z in zip(x2, y2, age_count):
        plt2.text(x - 0.1, y + 4, z)

    # 绘制不同年份的车对应数量 折线图
    plt3 = plt.subplot(2, 1, 2)
    x3 = np.arange(len(year_count))
    y3 = year_count
    plt3.plot(x3, y3, label='changes', linewidth=2, color='r', marker='*',
              markerfacecolor='blue', markersize=5)
    plt3.set_title("二手车上牌年份分布图")
    plt3.set_xlabel('年份')
    plt3.set_ylabel('数量/(辆)')
    plt3.set_xticks(np.arange(len(year_count)))
    plt3.set_xticklabels(year_count.index, rotation=30)
    # plt3.set_ylim([0, 400])
    for x, y, z in zip(x3, y3, year_count):
        plt3.text(x, y + 1, str(y), ha='center', va='bottom', fontsize=10, rotation=0)
    #     图例位置
    plt3.legend(loc="upper right")
    plt.subplots_adjust(wspace=0.5, hspace=0.5)
    # plt.show()
    plt.savefig(fname="../img/车龄分析.jpg", dpi=1000, facecolor="w")
    print("车龄分析图已保存")


# 实现贬值信息可视化分析
def diff_price(data):
    plt.figure(figsize=(10, 6))
    plt.suptitle('贬值关系分析')
    # 贬值差价与车龄分析
    # 车龄与贬值关系散点图
    plt1 = plt.subplot(2, 1, 1)
    x_data = data['车龄']
    y_data = data['贬值']
    plt1.scatter(x_data, y_data, s=2)
    plt1.set_xlabel('车龄/(年)')
    plt1.set_ylabel('贬值/(万元)')
    plt1.set_title('车龄与贬值关系散点图')

    # 里程与贬值关系散点图
    z_data = data['里程']
    plt2 = plt.subplot(2, 1, 2)
    plt2.scatter(z_data, y_data, s=2)
    plt2.set_xlabel('里程/(万公里)')
    plt2.set_ylabel('贬值/(万元)')
    plt2.set_title('里程与贬值关系散点图')

    plt.subplots_adjust(wspace=0, hspace=0.5)
    plt.savefig(fname="../img/贬值与车龄里程情况分析.jpg", dpi=1000, facecolor="w")
    # plt.show()
    print("贬值关系图已保存")


# 实现全国二手车分布图可视化
def place_scan(data):
    citys = data['所在地'].value_counts().keys()
    # print(citys.head())
    # print(citys.describe())
    values = data['所在地'].value_counts().values.astype('str')
    # 组成元祖组成的列表
    data_list = list(zip(citys, values))
    # print(data_list)

    c = (
        Geo(init_opts=opts.InitOpts(theme=ThemeType.MACARONS,
                                    width='1200px', height='600px'))
            .add_schema(maptype="china")
            .add(
            "二手车所在地全国分布图",
            data_list,
            type_=ChartType.EFFECT_SCATTER,
            is_selected=True, symbol=None, symbol_size=6, color="red"
        )
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(is_piecewise=True, max_=100))

            .render("../img/二手车所在地全国分布图.html")
    )
    print("全国分布图已保存")


if __name__ == '__main__':
    data = pd.read_excel('../数据/二手车处理后数据.xlsx')
    # print(data.head())
    price_plt(data)
    diff_price(data)
    place_scan(data)
    age_plt(data)
    print("all is ok！！！")
